#include <gtk/gtk.h>
#include <stdio.h>

#include "gtk_buffer.h"
#include "app.h"

static void button_run(GtkWidget *widget, gpointer data);
static void button_destroy(GtkWidget *widget, gpointer data);

void init_gtk(void)
{
    gtk_init(NULL, NULL);
    
    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_widget_set_usize((window), 1000, 500);
    gtk_window_set_resizable(GTK_WINDOW(window), FALSE);
    gtk_signal_connect(GTK_OBJECT(window),
            "destroy",
            G_CALLBACK(gtk_main_quit),
            NULL);

    box = gtk_vbox_new(FALSE,0);
    gtk_widget_show(box);

    buffer = gtk_text_buffer_new(NULL);
    view = gtk_text_view_new_with_buffer(buffer);
    /* 将组件加入盒子 */
    gtk_box_pack_start(GTK_BOX(box), view, TRUE, TRUE, 0);
    gtk_widget_set_size_request(view, 200, 150);

    button = gtk_button_new_with_label("运行");
    /* 将组件加入盒子 */
    gtk_box_pack_start(GTK_BOX(box), button, FALSE, FALSE, 10);
    g_signal_connect (G_OBJECT (button), "clicked",
                        G_CALLBACK(button_run), NULL);
    gtk_widget_show(button);

    button2 = gtk_button_new_with_label("退出");
    /* 将组件加入盒子 */
    gtk_box_pack_start(GTK_BOX(box), button2, FALSE, FALSE, 10);
    g_signal_connect (G_OBJECT (button2), "clicked",
                        G_CALLBACK(button_destroy), NULL);
    gtk_widget_show(button2);

    /* 将盒子加入窗口 */
    gtk_container_add(GTK_CONTAINER(window), box);
    gtk_widget_show(view);
   
    gtk_widget_show(window);
}

static void button_run(GtkWidget *widget, gpointer data)
{
    sem_post(&sem_run);
}

static void button_destroy(GtkWidget *widget, gpointer data)
{
    destroy();
}

void input_buffer(gchar *input_data)
{
    GtkTextIter start, end;
    //获得缓冲区开始和结束位置的Iter
    gtk_text_buffer_get_bounds(GTK_TEXT_BUFFER(buffer), &start, &end);
    //插入文本到缓冲区
    gtk_text_buffer_insert(GTK_TEXT_BUFFER(buffer), &start, input_data, strlen(input_data));
}
